﻿using System.Net;
using System.Text.Json;

public class CustomExceptionHandlingMiddleware
{
    private readonly RequestDelegate _next;

    public CustomExceptionHandlingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            if (context.Request.Headers.TryGetValue("Authorization", out var authorizationHeader))
            {
                var token = authorizationHeader.ToString().Replace("Bearer ", string.Empty);
                context.Request.Headers.Add("LUserInfo", token);
            }
            await _next(context);
            #region 没有权限
            if (context.Response.StatusCode == StatusCodes.Status403Forbidden)
            {
                // 设置自定义的错误信息  
                var errorMessage = new
                {
                    StatusCode = context.Response.StatusCode,
                    Message = "你无权访问此方法"
                };
                var errorJson = JsonSerializer.Serialize(errorMessage);
                // 设置新的状态码  
                context.Response.StatusCode = StatusCodes.Status403Forbidden;
                // 设置响应的内容类型  
                context.Response.ContentType = "application/json";
                // 写入自定义的响应体  
                await context.Response.WriteAsync(errorJson);
            }
            #endregion
            #region  token无效或者过期
            
            if (context.Response.StatusCode == StatusCodes.Status401Unauthorized)
            {
                // 设置自定义的错误信息  
                var errorMessage = new
                {
                    StatusCode = context.Response.StatusCode,
                    Message = "JWT令牌无效或已过期。"
                };
                var errorJson = JsonSerializer.Serialize(errorMessage);
                // 设置新的状态码  
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                // 设置响应的内容类型  
                context.Response.ContentType = "application/json";

                // 写入自定义的响应体  
                await context.Response.WriteAsync(errorJson);
            }
            #endregion
        }
        catch (Exception ex)
        {
            // 处理其他异常...  
            // 注意：在生产环境中，通常不会向客户端暴露详细的异常信息  
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.Response.ContentType = "application/json";
            var errorResponse = JsonSerializer.Serialize(new
            {
                StatusCode = context.Response.StatusCode,
                Message = "服务器内部错误。"
            });

            await context.Response.WriteAsync(errorResponse);

        }
    }

    // 其他异常处理逻辑...  
}
